import axios, {AxiosError} from 'axios'
import {useUserStore} from '@/store'
import {router} from "@/router";

const instance = axios.create({
    baseURL: `${import.meta.env.VITE_BASE_URL}`,
    timeout: 10000
})

// 请求拦截器
instance.interceptors.request.use((config) => {
        const token = useUserStore().userState.token
        config.headers['token'] = token ? token : ''
        return config
    },
    (error) => {
        return Promise.reject(error)
    })

// 响应拦截器
instance.interceptors.response.use(
    (response) => {
        const data = response.data
        let message = data.message
        if (data.code !== 200) {
            if (!message) {
                message = '网络异常'
            }
            console.log('error', message)
            ElMessage.error(message)
        }
        if (data.code === 401) {
            ElMessage.error('登录过期')
            router.push('/login')
            return Promise.reject(message)
        }
        if (data.code === 200) {
            return data
        } else {
            return Promise.reject(message)
        }
    },
    async (error: AxiosError) => {
        let message;
        console.log('error.response.data', error.response?.data);
        const status = error.response?.status;
        if (status === 401) {
            message = '登录过期'
            await router.push('/login')
        } else if (status === 403) {
            message = '没有权限'
        } else {
            message = '网络异常'
        }
        if (message) {
            error.message = message
        } else {
            error.message = '网络异常'
        }
        ElMessage.error(error.message)
        return Promise.reject(error)
    },
    {})

export default instance
